package com.corx.network.mysqlstorage.handler;

import com.corx.network.core.handler.DeviceStateHandler;
import com.corx.network.core.type.DeviceStateEnum;
import com.corx.network.mysqlstorage.hub.DeviceRepositoryHub;
import com.corx.network.mysqlstorage.model.Device;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * @author gx
 * @version 1.0.0
 */
@Slf4j
public class JdbcDeviceStateHandler implements DeviceStateHandler {

    private final DeviceRepositoryHub hub;

    public JdbcDeviceStateHandler(DeviceRepositoryHub hub) {
        this.hub = hub;
    }

    @Override
    public void onChange(String deviceId, DeviceStateEnum state) {
        if (deviceId == null || deviceId.isEmpty()) {
            log.warn("JdbcDeviceStateHandler处理器，接收到的deviceId是空的 return，不做任何处理");
            return;
        }
        Optional<Device> optional = hub.deviceRepo().findById(Long.parseLong(deviceId));
        if (!optional.isPresent()) {
            log.warn("JdbcDeviceStateHandler处理器，根据设备deviceId查询不到数据 return，不做任何处理");
            return;
        }
        Device device = optional.get();
        device.setState(state.getState());
        hub.deviceRepo().update(device);
    }

}
